package com.nari.ysphd.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

/**
 * Created by Administrator on 2018/6/14.
 */

public class Lengthwatch implements TextWatcher {

    private int Max;
    private EditText editText;

    public Lengthwatch(EditText editText, int Max) {
        this.Max = Max;
        this.editText = editText;
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
//        String text=editText.getText().toString();
//        int inputByteLength=0;
//        for(int i=0;i<text.length();i++){
//            inputByteLength+=text.substring(i, i+1).getBytes().length;
//        }
//
//        int beforByteLength=0;
//        String beforString = s.toString();
//        for(int i=0;i<beforString.length();i++){
//            beforByteLength+=beforString.substring(i, i+1).getBytes().length;
//        }
//
//        if(inputByteLength > Max){
//            editText.setText(s);
//            editText.setSelection(editText.getText().toString().length());
//            return;
//        }
    }

    @Override
    public void afterTextChanged(Editable s) {
        String text=editText.getText().toString();
        int maxStringLength=0;
        int inputByteLength=0;
        for(int i=0;i<text.length();i++){
            inputByteLength+=text.substring(i, i+1).getBytes().length;
            if(inputByteLength > Max){
                maxStringLength=i;
            }
        }
        if(inputByteLength > Max){
            editText.setText(s.subSequence(0, maxStringLength));
            editText.setSelection(editText.getText().toString().length());
            return;
        }
    }
}
